package com.meessiom.train.crm.user.service;

import com.meessiom.train.crm.common.exception.ResourceNotFoundException;
import com.meessiom.train.crm.user.model.User;
import com.meessiom.train.crm.user.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service

public class UserService {
    @Autowired
    private UserRepository userRepository;


    public List<User> getAllUser(){
        return userRepository.findAll();
    }


    public User createUser(User user){

        return userRepository.save(user);
    }


    public User getUserById(long id){
       User user = userRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException
                ("User not exist with id" + id));
        return user;
    }

    public String getUserNameByUserId(long id){
        String userName = userRepository.getUserNameByUserId(id);
        return userName;
    }

    public User updateUser(long id, User userDetails){
      User updateUser = userRepository.findById(id).orElseThrow(()
              -> new ResourceNotFoundException("User not exist with id" + id));
        updateUser.setUserName(userDetails.getUserName());
        updateUser.setUserPhone(userDetails.getUserPhone());
        updateUser.setUserAddress(userDetails.getUserAddress());

        userRepository.save(updateUser);
        return updateUser;
    }


    public void deleteUser(long id){
        User user = userRepository.findById(id).orElseThrow(() ->
                new ResourceNotFoundException("User not exist with id" + id));

        userRepository.delete(user);
    }

}
